<?php

namespace App\Http\Controllers\Frontend\V10\Users;

use App\Events\AuthStepEvent;
use App\Exceptions\GeneralException;
use App\Facades\SamLogFacade;
use App\Http\Requests\Frontend\V10\Users\UserZhiMaStoreRequest;
use App\Models\UserAuthStepEventLog;
use App\Models\UserLoanRequest;
use App\Models\UserZhiMaInfo;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class UserZhiMaController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:api');
    }

    /**
     * Description:录入用户芝麻信用认证结果
     * Author: Sam
     * DateTime: 2019/1/4 19:51
     * @param UserZhiMaStoreRequest $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function store(UserZhiMaStoreRequest $request)
    {
        $user = Auth::user();
        $params = $this->extractInputFromRules($request,$request->rules());
        $params['user_id'] = $user->id;
        $loan = UserLoanRequest::where(['current'=>UserLoanRequest::CURRENT_NOW,'user_id'=>$user->id])->orderByDesc('id')->firstOrFail();
        DB::beginTransaction();
        try{
            Log::debug('zhima-create:'.json_encode($params, 256));
            $info = UserZhiMaInfo::create($params);
            $loan->zhima_id = $info->id;
            $loan->save();
            $log = [
                'uid'=>$user->id,
                'step_id'=>$info->id,
                'type'=>UserAuthStepEventLog::STEP_ZHIMA,
                'loan_request_id'=>$loan->id,
            ];
            event(new AuthStepEvent($log));
            DB::commit();
        }catch (\Exception $exception){
            SamLogFacade::debug($exception->getMessage());
            DB::rollBack();
            throw new GeneralException($exception->getMessage(),500);
        }
        return success($info);
    }
}
